package com.hlm.transparent.core.handler;

import com.hlm.transparent.core.check.CJT188Check;
import com.hlm.transparent.core.check.ModBusCheck;
import com.hlm.transparent.core.command.CJT188Command;
import com.hlm.transparent.core.resolve.CJT188Resolve;
import com.hlm.transparent.core.resolve.ModBusResolve;
import com.hlm.transparent.model.SocketMap;
import com.hlm.transparent.model.TransparentData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

/**
 * @program:transparent
 * @description:
 * @author: xinY
 **/
@Component
public class SocketInHandler extends ChannelInboundHandlerAdapter{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接受到数据包："+ByteBufUtil.hexDump((ByteBuf)msg));
        ByteBuf byteBuf = (ByteBuf)msg;
        //判断协议
        String protocolCode = "";
        // addr
        String addr = "";
        String mssg = "";
        if (protocolCode.startsWith("C")){
//        System.out.println(commandBuf.readableBytes()+"下发命令包长度");
             mssg = "报文校验失败";
                // 检查 有一包成功就行
                if(CJT188Check.check(byteBuf,byteBuf)){
                    mssg = "报文校验成功，开始解析";
                    // 解析 返回一个dataentity
                    TransparentData dataEntity = CJT188Resolve.resolve(byteBuf,protocolCode);
                }

        }
        if (protocolCode.startsWith("m")){

            mssg = "报文校验成功";
            // modbus 如果有一包失败就失败
            if (!ModBusCheck.check(byteBuf,byteBuf)){
                TransparentData dataEntity = ModBusResolve.resolve(byteBuf,protocolCode);
                mssg = "报文校验失败";
            }
        }
        if (protocolCode.startsWith("E")){

        }
        System.out.println(mssg);
    }

    /**
     * 发包是在想发的时候发
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        System.out.println("客户端："+ctx.channel().remoteAddress().toString()+"上线了");
        String socketId = ctx.channel().remoteAddress().toString();
        SocketMap.set (socketId,ctx);
    }
}
